<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.tag_name"
        placeholder="标签名称"
        style="width: 200px;"
        class="filter-item"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="getList"
      >搜索</el-button>
      <el-button
        class="filter-item"
        style="margin-bottom: unset;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加标签</el-button>
    </div>
    <br>
    <!-- 数据列表区域 -->
    <!-- :data 指定数据源 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <!-- 表格索引 -->
      <el-table-column type="index" align="center" label="表格索引" width="50" />

      <el-table-column align="center" label="ID" width="80">
        <!-- v-slot="scope" 作用域插槽渲染获取数据。scope.row 获取此行数据，.id  获取详细数据 -->
        <template v-slot="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="标签名称" width="auto">
        <template v-slot="scope">
          <span style="white-space: pre-line;">{{ scope.row.tag_name }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template v-slot="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="scope.row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="deleteRow(scope.$index, list, scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页配置 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 添加 or 更新 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="80px"
        style="width: 400px; margin-left:80px;"
      >
        <el-form-item label="标签内容" prop="tag_name">
          <!-- el-input  添加  disabled 可以禁止修改数据-->
          <el-input
            v-model="temp.tag_name"
            :autosize="{ minRows: 5, maxRows: 8 }"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchTagList, deleteTag, createTag, editTag } from '@/api/tag'
import Pagination from '@/components/Pagination'

export default {
  name: 'Tag',
  components: { Pagination },
  // 当前组件的基本数据
  data() {
    return {
      // 获取列表
      list: null,
      total: 0,
      listLoading: true,
      // 获取数据列表的参数对象
      listQuery: {
        page: 1,
        limit: 5,
        tag_name: ''
      },
      // 查询到的 内容对象保存
      temp: {
        tag_name: ''
      },
      // 控制弹窗的显示与隐藏
      dialogFormVisible: false,
      // 判断操作是 更新 or 添加
      dialogStatus: '',
      textMap: {
        updata: '更新标签',
        create: '添加标签'
      },
      // 表单验证规则
      rules: {
        // 使用 prop="tag_name" 引用
        tag_name: [{ required: true, message: '内容不能为空', trigger: 'blur' }]
      }
    }
  },
  // 周期函数，刷新数据列表
  created() {
    this.getList()
  },

  // 添加事件函数
  methods: {
    // 获取数据列表
    getList() {
      this.listLoading = true
      fetchTagList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 删除数据
    deleteRow(index, row, id) {
      // 使用MessageBox弹窗完成删除功能
      this.$confirm('此操作将永久删除该内容, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteTag(id).then(response => {
            row.splice(index, 1)
            this.$message({
              type: 'success',
              message: '删除成功',
              duration: 1000
            })
          })
        })
    },

    // 添加数据 内容对象保存
    resetTemp() {
      this.temp = {
        tag_name: ''
      }
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      // $refs 表单的预验证功能，验证表单的验证规则
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 传递创建数据
          createTag(this.temp).then(response => {
            this.list.unshift(response.data)
            // 关闭弹窗
            this.dialogFormVisible = false
            // 添加数据成功
            this.$notify({
              title: 'Success',
              type: 'success',
              message: '添加成功',
              duration: 1000
            })
          })
        }
      })
    },
    // 更新数据
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'updata'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        editTag(this.temp.id, this.temp).then(() => {
          for (const v of this.list) {
            if (v.id === this.temp.id) {
              const index = this.list.indexOf(v)
              this.list.splice(index, 1, this.temp)
              break
            }
          }
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: '更新成功',
            type: 'success',
            duration: 1000
          })
        })
      })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
